package Ldap_app;
use Mojo::Base 'Mojolicious';
use Mojolicious::Plugin::Mail;
use Crypt::CBC;
use Net::LDAP;

# This method will run once at server start
sub startup {
    my $self   = shift;
    my $config = $self->plugin('Config');
    $self->helper(
        encrypt => sub {
            my $self   = shift;
            my $mail   = shift;
            my $time   = time();
            my $cipher = Crypt::CBC->new(
                -key    => $config->{crypt_key},
                -cipher => 'Blowfish'
            );
            my $string = join( ":", $mail, $time );
            my $encrypted = $cipher->encrypt_hex($string);
            return $encrypted;
        }
    );

    $self->helper(
        decrypt => sub {
            my $self      = shift;
            my $encrypted = shift;
            my $cipher    = Crypt::CBC->new( -key => $config->{crypt_key},-cipher => 'Blowfish', );
            my $decrypted = $cipher->decrypt_hex($encrypted);
            return $decrypted;
        }
    );

    $self->helper(
        expired => sub {
            my $self       = shift;
            my $token_time = shift;
            my $time       = time;
            return 1 if ( $time - $config->{expired} > $token_time );
            return 0;
        }
    );

    $self->helper(
        ldap => sub {
            my $ldap =
              Net::LDAP->new( $config->{ldap_host},
                port => $config->{ldap_port} ,version => 3)  or $self->log->info('cant connect to ldap server');
            $ldap->bind(
                dn       => $config->{admin},
                password => $config->{password}
            );

            return $ldap;
        }
    );

    $self->helper(
        search_mail => sub {
        my $self=shift;
        my $mail=shift; 
        #$self->app->log->info("search $mail");
        my $resp=$self->ldap->search(
        base   => $config->{ldap_dn},
        filter => "(mail=$mail)",
        attrs  => ['mail','userPassword'] ,
        );
         return $resp;
        }
    );


    $self->plugin(
        mail => {
            from    => $config->{email},
            type    => 'text/html',
            how     => 'smtp',
            howargs => [
                $config->{smtp},
                AuthUser => $config->{AuthUser},
                AuthPass => $config->{AuthPass},
            ],
        }
    );

    # Router
    my $r = $self->routes;

    # Normal route to controller
    $r->get('/')->to('example#welcome');
    my $act = $r->under("/action/");
    $act->route("/update")->via('get')->to("Utils#confirm")->name('flush pager');
    $act->route("/update")->via('post')->to("Utils#flush")->name('flush done');
    $act->route("/apply")->via('post')->to("Utils#apply")->name('apply');
}

1;
